package com.example.pay.util;

import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.io.InputStream;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * 加载PEM内容的工具：支持直接PEM文本、绝对/相对文件路径、以及classpath资源。
 */
public class PemUtil {

    /**
     * 传入配置值，如果以"-----BEGIN"开头则视为PEM文本；
     * 否则尝试按文件路径读取；若以"classpath:"前缀则从classpath读取。
     */
    public static String loadPem(String configValue) {
        if (configValue == null || configValue.trim().isEmpty()) {
            throw new IllegalArgumentException("PEM配置值为空");
        }
        String v = configValue.trim();
        if (v.startsWith("-----BEGIN")) {
            return v;
        }

        // classpath资源
        if (v.startsWith("classpath:")) {
            String path = v.substring("classpath:".length());
            try {
                ClassPathResource resource = new ClassPathResource(path);
                if (!resource.exists()) {
                    throw new IllegalArgumentException("Classpath资源不存在: " + path);
                }
                try (InputStream is = resource.getInputStream()) {
                    byte[] bytes = readAllBytes(is);
                    return new String(bytes, StandardCharsets.UTF_8);
                }
            } catch (IOException e) {
                throw new RuntimeException("读取classpath资源失败: " + path, e);
            }
        }

        // 文件路径（绝对或相对）
        try {
            byte[] bytes = Files.readAllBytes(Paths.get(v));
            return new String(bytes, StandardCharsets.UTF_8);
        } catch (IOException e) {
            throw new RuntimeException("读取PEM文件失败: " + v, e);
        }
    }

    // JDK8没有InputStream#readAllBytes，提供兼容实现
    private static byte[] readAllBytes(InputStream in) throws IOException {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        byte[] data = new byte[8192];
        int n;
        while ((n = in.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, n);
        }
        return buffer.toByteArray();
    }
}